const WebSocket = require("ws");

// 创建 WebSocket 服务器
const wss = new WebSocket.Server({ port: 8080 });

wss.on("connection", (ws) => {
    console.log("新的客户端已连接");

    // 接收客户端消息
    ws.on("message", (message) => {
        console.log("收到消息:", message.toString());

        // 广播消息给所有客户端
        wss.clients.forEach((client) => {
            if (client !== ws && client.readyState === WebSocket.OPEN) {
                client.send(message.toString());
            }
        });
    });

    // 处理客户端断开连接
    ws.on("close", () => {
        console.log("客户端已断开连接");
    });
});

console.log("WebSocket 服务器已启动，监听端口 8080");